<template>
  <div class="container">
    <div class="context">
      <el-card style="min-width: 600px">
        <template #header>
          <div class="card-header">
            <span>用户信息</span>
            <el-button type="danger" @click="managerStore.isShow = false" class="button-close">
              <el-icon><CircleCloseFilled /></el-icon>
              Close
            </el-button>
          </div>
        </template>
        <div class="card-body-top">
          <el-button type="info" plain @click="dialogVisible = true" style="margin-bottom: 10px"
            >新增用户</el-button
          >
          <el-input
            v-model="input"
            style="width: 240px; margin-bottom: 10px"
            placeholder="搜索用户名"
            :prefix-icon="Search"
            @input="handleSearch"
          />
        </div>
        <el-table
          :data="tableData"
          border
          stripe
          style="width: 100%"
          :cell-style="{ textAlign: 'center' }"
          :header-cell-style="{ 'text-align': 'center' }"
        >
          <el-table-column prop="username" label="用户名" width="120" />
          <el-table-column
            prop="type"
            label="用户类型"
            width="120"
            :filters="[
              { text: '管理员', value: '管理员' },
              { text: '交通部门', value: '交通部门' },
              { text: '普通用户', value: '普通用户' }
            ]"
            :filter-method="filterHandler"
          />
          <el-table-column
            prop="isOnline"
            label="登录状态"
            width="120"
            :filters="[
              { text: '在线', value: '在线' },
              { text: '离线', value: '离线' }
            ]"
            :filter-method="filterHandler"
          />
          <el-table-column label="操作">
            <template #default="{ row, $index }">
              <div v-if="shouldShowRow(row)">
                <el-button type="success" size="small" @click="handleEdit(row)"> 修改 </el-button>
                <el-popconfirm title="确定删除该用户吗？" confirm-button-text="确定"  @confirm="handleDelete(row)" cancel-button-text="取消" @cancel="handleCancel" hide-after="duration">
                  <template #reference>
                    <el-button type="danger" size="small">
                      删除
                    </el-button>
                  </template>
                </el-popconfirm>
                <el-button
                  type="warning"
                  size="small"
                  v-if="row.isOnline === '在线'"
                  @click="handleOffline(row)"
                >
                  下线
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <template #footer
          ><el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[5, 6, 7, 8, 9, 10]"
            :total="total"
            small
            background
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        /></template>
      </el-card>
      <el-dialog v-model="dialogFormVisible" title="修改用户名和密码" width="500" draggable>
        <el-form :model="form">
          <el-form-item label="用户名">
            <el-input v-model="form.username" />
          </el-form-item>
          <el-form-item label="密码">
            <el-input v-model="form.password" type="password" show-password />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false"> 取消 </el-button>
            <el-button type="primary" @click="handleConfirmChange"> 确认 </el-button>
          </div>
        </template>
      </el-dialog>
      <el-dialog v-model="dialogVisible" title="新增用户" width="500" draggable>
        <el-form :model="form">
          <el-form-item label="用户名">
            <el-input v-model="form.username" />
          </el-form-item>
          <el-form-item label="密码">
            <el-input v-model="form.password" type="password" show-password />
          </el-form-item>
          <el-form-item label="用户类型">
            <el-select v-model="form.type" placeholder="请选择">
              <el-option label="交通部门" value="traffic" />
              <el-option label="普通用户" value="common" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false"> 取消 </el-button>
            <el-button type="primary" @click="handleAdd"> 确认 </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import {
  register,
  getUserInfo,
  deleteUser,
  changeUserInfo,
  logoutUser
} from '@/hook/user-api/userState.js'
import { useManagerStoreWithOut } from '@/stores/manager'
import { CircleCloseFilled, Search } from '@element-plus/icons-vue'

const managerStore = useManagerStoreWithOut()
const dialogFormVisible = ref(false)
const dialogVisible = ref(false)
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
const duration = ref(3000)
const input = ref('')
let user = ref([])
const form = reactive({
  username: '',
  type: '',
  password: '',
  id: ''
})

// 定义获取数据的方法
async function fetchData() {
  const userArr = ['admin', 'traffic', 'common']
  // 异步请求用户信息
  const userInfo = await Promise.all(userArr.map((item) => getUserInfo(item)))
  // 处理数据
  console.log('userInfo: ', userInfo)
  let user = userInfo.map((item) => item.data.result)
  //展开数组
  user = user.flat()
  user = user.map((item) => {
    return {
      username: item.username,
      type: item.type === 'common' ? '普通用户' : item.type === 'traffic' ? '交通部门' : '管理员',
      isOnline: item.isOnline ? '在线' : '离线'
    }
  })
  return user
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  tableData.value = user.value.slice((val - 1) * pageSize.value, val * pageSize.value)
  console.log('current page: ', val)
}

// 处理每页显示条数变化
const handleSizeChange = (val) => {
  pageSize.value = val
  tableData.value = user.value.slice((currentPage.value - 1) * val, currentPage.value * val)
  console.log('page size: ', val)
}
// 管理者不显示操作
const shouldShowRow = (row) => {
  return row.username !== 'admin'
}

//打开修改弹窗
const handleEdit = (row) => {
  dialogFormVisible.value = true
  const type = row.type === '管理员' ? 'admin' : row.type === '交通部门' ? 'traffic' : 'common'
  getUserInfo(type).then((res) => {
    res.data.result.find((item) => {
      if (item.username === row.username) {
        form.username = item.username
        form.password = item.password
        form.id = item.id
        form.type = type
        return form
      }
    })
  })
}

// 处理取消
const handleCancel = () => {
  duration.value = 0
}

// 处理修改
const handleConfirmChange = (row) => {
  changeUserInfo(form)
  dialogFormVisible.value = false
  user.value = user.value.map((item) => {
    if (item.username === row.username) {
      item.username = form.username
    }
    return item
  })
  tableData.value = user.value.slice(
    (currentPage.value - 1) * pageSize.value,
    currentPage.value * pageSize.value
  )
  total.value = user.value.length
}
// 处理删除
const handleDelete = (row) => {
  deleteUser(
    row.username,
    row.type === '管理员' ? 'admin' : row.type === '交通部门' ? 'traffic' : 'common'
  )
  user.value = user.value.filter((item) => item.username !== row.username)
  tableData.value = user.value.slice(
    (currentPage.value - 1) * pageSize.value,
    currentPage.value * pageSize.value
  )
  total.value = user.value.length
}

// 处理下线
const handleOffline = (row) => {
  console.log('offline: ', row)
  logoutUser(
    row.username,
    row.type === '管理员' ? 'admin' : row.type === '交通部门' ? 'traffic' : 'common'
  )

  user.value = user.value.map((item) => {
    if (item.username === row.username) {
      item.isOnline = '离线'
    }
    return item
  })
  tableData.value = user.value.slice(
    (currentPage.value - 1) * pageSize.value,
    currentPage.value * pageSize.value
  )
  total.value = user.value.length
}

// 处理搜索
const handleSearch = () => {
  const keyword = input.value.trim()
  if (keyword === '') {
    tableData.value = user.value.slice(
      (currentPage.value - 1) * pageSize.value,
      currentPage.value * pageSize.value
    )
    return
  }
  const filterData = user.value.filter((item) => {
    return item.username.includes(keyword)
  })
  tableData.value = filterData.slice(
    (currentPage.value - 1) * pageSize.value,
    currentPage.value * pageSize.value
  )
}

// 处理筛选
const filterHandler = (value, row, column) => {
  const property = column['property']
  return row[property] === value
}

// 新增用户
const handleAdd = () => {
  register(form.username, form.password, form.password, form.type)
  dialogVisible.value = false
  user.value = [
    ...user.value,
    {
      username: form.username,
      type: form.type === 'common' ? '普通用户' : '交通部门',
      isOnline: '离线'
    }
  ]
  tableData.value = user.value.slice(
    (currentPage.value - 1) * pageSize.value,
    currentPage.value * pageSize.value
  )
  total.value = user.value.length
}

onMounted(async () => {
  user.value = await fetchData()
  total.value = user.value.length
  tableData.value = user.value.slice(0, pageSize.value)
})
</script>

<style lang="scss" scoped>
.container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  padding-left: 2rem;
  padding-right: 2rem;
  display: flex;
  justify-content: center;
  --tw-text-opacity: 1;
  --tw-bg-opacity: 0.3;
  color: rgb(0 0 0 / var(--tw-text-opacity));
  background-color: rgb(0 0 0 / var(--tw-bg-opacity));
  z-index: 20;
  .context {
    align-self: flex-start;
    padding: 5rem;
    :deep(.el-card__header) {
      position: relative;
      .button-close {
        position: absolute;
        top: 10px;
        right: 10px;
      }
    }
    .card-body-top {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
}
</style>
